package com.bstek.uflo.form.command;

import java.util.Map;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.util.StringUtils;

import com.bstek.uflo.command.Command;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.form.Constants;

/**
 * @author Jacky.gao
 * @since 2013年11月15日
 */
public class GetTableDataCommand implements Command<Map<String, Object>> {
	private Object keyValue;
	private String sql;
	private String slaveSql;

	public GetTableDataCommand(String sql,String slaveSql, Object keyValue) {
		this.keyValue = keyValue;
		this.sql = sql;
		this.slaveSql=slaveSql;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> execute(Context context) {
		Session session = context.getSession();
		SQLQuery query = session.createSQLQuery(sql);
		if (keyValue instanceof Integer) {
			query.setInteger(0, (Integer) keyValue);
		} else if (keyValue instanceof Long) {
			query.setLong(0, (Long) keyValue);
		} else {
			query.setString(0, (String) keyValue);
		}
		query.setResultTransformer(new MapResultTransformer());
		Map<String, Object> result=(Map<String, Object>)query.uniqueResult();
		if(StringUtils.hasText(slaveSql)){
			SQLQuery slaveQuery = session.createSQLQuery(slaveSql);
			if (keyValue instanceof Integer) {
				slaveQuery.setInteger(0, (Integer) keyValue);
			} else if (keyValue instanceof Long) {
				slaveQuery.setLong(0, (Long) keyValue);
			} else {
				slaveQuery.setString(0, (String) keyValue);
			}
			slaveQuery.setResultTransformer(new MapResultTransformer());
			result.put(Constants.SLAVE_PROPERTY, slaveQuery.list());
		}
		return result;
	}
}
